package net.ib.mtalk.ui.buddy.talk;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Vector;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.BuddyInfo;
import net.ib.mntalk.protocol.Common.UserBasicInfo;
import net.ib.mntalk.protocol.Session.GetBuddyInfosReq;
import net.ib.mntalk.protocol.Session.SearchBuddyReq;
import net.ib.mtalk.R;
import net.ib.mtalk.base.BaseFragmentActivity;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.database.DatabaseContract.BuddyTable;
import net.ib.mtalk.database.DatabaseContract.ContactTable;
import net.ib.mtalk.database.helper.BuddyDatabaseHelper;
import net.ib.mtalk.database.helper.NotifyingAsyncQueryHandler;
import net.ib.mtalk.ui.ActivityResult;
import net.ib.mtalk.ui.buddy.BuddyTabActivity;
import net.ib.mtalk.ui.buddy.group.EditGroup;
import net.ib.mtalk.ui.buddy.item.BuddyActionItem;
import net.ib.mtalk.ui.buddy.item.BuddyUUIDItem;
import net.ib.mtalk.ui.buddy.item.ChildrenItem;
import net.ib.mtalk.ui.buddy.item.GroupItem;
import net.ib.mtalk.ui.buddy.item.BuddyActionItem.ItemType;
import net.ib.mtalk.ui.favorite.FavoriteActivity.FavoriteFragment;
import net.ib.mtalk.ui.fragment.ExpandableListFragment;
import net.ib.mtalk.ui.inbox.InboxController;
import net.ib.mtalk.ui.setting.SettingsActivity;
import net.ib.mtalk.ui.widget.QuickAction;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.MTalkLogWriter;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.RecognizerIntent;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.support.v4.widget.CursorAdapter;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewParent;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;

import com.google.protobuf.micro.InvalidProtocolBufferMicroException;

public class BuddyTalkListActivity extends BaseFragmentActivity implements OnClickListener{
	private Context mContext;
	Vector<String> buddies = new Vector<String>();
	Cursor buddy_cursor;
	String[] allbudies;
	static List<BuddyUUIDItem> checkedPerson = new ArrayList<BuddyUUIDItem>();
	private BuddyTalkController mUiController;
	private InboxController mInboxController;
	LinearLayout layout;
	private Button btn_groupChat;
	private Button btn_groupMessage;
	private Button btn_cancel;
	public static EditText searchBuddy;
	private ImageButton voice_btn;
	private static NotifyingAsyncQueryHandler queryHandler;
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case HandlerMsgConst.HANDLER_BLOCK_BUDDY_SUCCESS:
				Toast.makeText(mContext, "HANDLER_BLOCK_BUDDY_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_BLOCK_BUDDY_FAIL:
				Toast.makeText(mContext, "HANDLER_BLOCK_BUDDY_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_REMOVE_BUDDY_SUCCESS:
				Toast.makeText(mContext, "HANDLER_REMOVE_BUDDY_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_REMOVE_BUDDY_FAIL:
				Toast.makeText(mContext, "HANDLER_REMOVE_BUDDY_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_UNKNOWN_ERROR:
				Toast.makeText(mContext, "HANDLER_UNKNOWN_ERROR", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_ADD_CONTACTS_SUCCESS:
				Toast.makeText(mContext, "HANDLER_ADD_CONTACTS_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_ADD_CONTACTS_FAIL:
				Toast.makeText(mContext, "HANDLER_ADD_CONTACTS_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_GET_BUDDY_CHANGES_SUCCESS:
				Toast.makeText(mContext, "HANDLER_GET_BUDDY_CHANGES_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_GET_BUDDY_CHANGES_FAIL:
				Toast.makeText(mContext, "HANDLER_GET_BUDDY_CHANGES_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_GET_BUDDY_INFOS_SUCCESS:
				Toast.makeText(mContext, "HANDLER_GET_BUDDY_INFOS_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_GET_CONTACTS_SUCCESS:
				Toast.makeText(mContext, "HANDLER_GET_CONTACTS_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_GET_CONTACTS_FAIL:
				Toast.makeText(mContext, "HANDLER_GET_CONTACTS_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_SET_BUDDY_INFO_SUCCESS:
				Toast.makeText(mContext, "HANDLER_SET_BUDDY_INFO_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_SET_BUDDY_INFO_FAIL:
				Toast.makeText(mContext, "HANDLER_SET_BUDDY_INFO_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_SEARCHBUDDY_SUCCESS:
				Toast.makeText(mContext, "HANDLER_SEARCHBUDDY_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_SEARCHBUDDY_NOT_EXIST:
				Toast.makeText(mContext, R.string.not_exist_user, Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_SEARCHBUDDY_FAIL:
				Toast.makeText(mContext, "HANDLER_SEARCHBUDDY_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_ALREADY_FRIEND:
				Toast.makeText(mContext, "HANDLER_ALREADY_FRIEND", Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};
	
	private int mode = 0;
	private static boolean showcheckbox = false;
	
	public static final int ADD_FRIEND     = 0;
	public static final int GROUP_MODE     = 1;
	public static final int SHOW_ALL	   = 2;
	public static final int SETTING   	   = 3;
	public static final int GROUP_CHATTING = 4;
	public static final int GROUP_MESSAGE  = 5;
	public static final int CANCEL   	   = 6;
	public static final int EDITGROUP	   = 7;
	public static final int MTALK_ID	   = 8;
	public static final int EMAIL		   = 9;
	
	public static final int SHOW_ALPHABET  = 10;
	public static final int SHOW_GROUP	   = 11;
	
	static BuddyTalkListFragment list = null;
	static LinearLayout searcdh_bar;
	
	private static final int QUERY_BUDDY = 0;
	private static final int QUERY_BUDDY_GROUP = 1;
	
	public static final int REQ_TALK_VOICE_RECOGNITION = 100;
	private AlertDialog alertDialog = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_buddy_contact_list);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		showcheckbox = false;
		mode = SHOW_ALPHABET;	//  모드 초기화
		
		mContext = this;
		mUiController = new BuddyTalkController(mContext, mHandler);
		mInboxController = new InboxController(mContext, mHandler);
		
		FragmentManager fm = getSupportFragmentManager();
		if(savedInstanceState == null) {
			list = new BuddyTalkListFragment();
			list.setArguments(savedInstanceState);
			fm.beginTransaction().add(R.id.buddy_talk_list, list).commit();
		}
		// 검색 바
		searcdh_bar = (LinearLayout) findViewById(R.id.searcdh_bar);
		searchBuddy = (EditText)findViewById(R.id.buddy_search);
		searchBuddy.addTextChangedListener(watcher());
		// 보이스 검색
		voice_btn = (ImageButton) findViewById(R.id.buddy_voice_btn);
		voice_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
				intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
				intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.buddy_voice_recognition));
				getParent().startActivityForResult(intent, REQ_TALK_VOICE_RECOGNITION);
			}
		});
		
		layout = (LinearLayout)findViewById(R.id.bc_layout01);
		btn_groupChat = (Button) findViewById(R.id.btn_groupChat);
		btn_groupChat.setOnClickListener(this);
		btn_groupMessage = (Button) findViewById(R.id.btn_groupMessage);
		btn_groupMessage.setOnClickListener(this);
		btn_cancel = (Button) findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(this);
	}
	
	private static TextWatcher watcher() {
		TextWatcher textWatcher = new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,	int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				list.mBuddyObserver.onChange(true);
			}
		};
		return textWatcher;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		menu.clear();
		if(!showcheckbox){
			menu.add(0, GROUP_MODE, 0, R.string.buddy_talk_groupmode).setIcon(R.drawable.menu_icon_group);
			SubMenu subMenu = menu.addSubMenu(0, ADD_FRIEND, 0, R.string.buddy_talk_addfriend).setIcon(R.drawable.menu_icon_addfriend);
			subMenu.add(0, MTALK_ID, 0, R.string.mtalk_id);
			subMenu.add(0, EMAIL, 0, R.string.email);

			if(mode == SHOW_ALPHABET){
				menu.add(0, SHOW_GROUP, 0, R.string.buddy_talk_showgroup).setIcon(R.drawable.menu_icon_grouplist);
			} else {
				menu.add(0, SHOW_ALL, 0, R.string.buddy_talk_showall).setIcon(R.drawable.menu_icon_all);
				menu.add(0, EDITGROUP, 0 , R.string.buddy_talk_editgroup).setIcon(R.drawable.menu_icon_grouplist_edit);
			}
			menu.add(0, SETTING, 0, R.string.settings).setIcon(R.drawable.menu_icon_settings);
//			menu.add(0, 99, 0, "모든 버디 삭제 후 추가(테스트 용)");
			return true;
		} else return false;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		if(item.getItemId() == GROUP_MODE){
			showcheckbox = true;
			layout.setVisibility(View.VISIBLE);
			if(mode == SHOW_GROUP) changeGroup();
			else changeShowAll();
		} else if(item.getItemId() == SHOW_GROUP){
			mode = SHOW_GROUP;
			changeGroup();
		} else if(item.getItemId() == SHOW_ALL){
			mode = SHOW_ALPHABET;
			changeShowAll();

		} else if(item.getItemId() == SETTING){
			Intent intent = new Intent(this, SettingsActivity.class);
			startActivity(intent);

		} else if(item.getItemId() == CANCEL){
			showcheckbox = false;
			layout.setVisibility(View.GONE);
			if(mode == SHOW_GROUP) changeGroup();
			else changeShowAll();
		} else if(item.getItemId() == EDITGROUP){
			Intent intent = new Intent(this, EditGroup.class);
			startActivity(intent);
		} else if(item.getItemId() == 99){
			BuddyDatabaseHelper.removeAllBuddy(mContext);
			
			GetBuddyInfosReq getBuddyInfosReq = new GetBuddyInfosReq();
			getBuddyInfosReq.setPredicate(new Common.UUIDSlicePredicate().setSliceRange((new Common.UUIDSliceRange().setAscending(true).setMaxCount(100))));
			getBuddyInfosReq.addProperty(Common.USER_PROPERTY_NAME).addProperty(Common.USER_PROPERTY_PROFILE_IMAGE).addProperty(Common.USER_PROPERTY_STATUS).addProperty(Common.USER_PROPERTY_BIRTHDAY).addProperty(Common.USER_PROPERTY_PRESENCE);
			mUiController.getBuddyInfos(getBuddyInfosReq);
		} else if(item.getItemId() == MTALK_ID){
			DialogAddFriend(Common.MnTalkID);
		} else if(item.getItemId() == EMAIL){	
			DialogAddFriend(Common.Email);
		}			
		return super.onMenuItemSelected(featureId, item);
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		return super.onCreateDialog(id);
	}

	private void DialogAddFriend(final int type) {
		LayoutInflater inflater = getLayoutInflater();
		View view = inflater.inflate(R.layout.dialog_add_friend, null, true);
		final EditText editText = (EditText) view.findViewById(R.id.add_friend_edit);
		if(type == Common.MnTalkID){
			((TextView)view.findViewById(R.id.add_friend_text)).setText(R.string.buddy_add_friend_id);
			editText.setHint(R.string.buddy_add_friend_id);
		} else {
			((TextView)view.findViewById(R.id.add_friend_text)).setText(R.string.buddy_add_friend_email);
			editText.setHint(R.string.buddy_add_friend_email);
		}

		Button btn_add_friend = (Button) view.findViewById(R.id.btn_add_friend);
		Button btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
		
		btn_add_friend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(editText.getText().toString().equals("")){
					if(type == Common.MnTalkID){
						Toast.makeText(mContext, getString(R.string.buddy_add_friend_id), Toast.LENGTH_LONG).show();
					}else{
						Toast.makeText(mContext, getString(R.string.buddy_add_friend_email), Toast.LENGTH_LONG).show();
					}
				} else {
					SearchBuddyReq searchBuddyReq = new SearchBuddyReq();
					searchBuddyReq.setAccountId(new Common.AccountId().setIdentifier(editText.getText().toString())
																	  .setType(type));
					mUiController.searchBuddy(searchBuddyReq);
					alertDialog.dismiss();
				}
			}
		});
		btn_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
			}
		});
		
		AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
		builder.setTitle(R.string.buddy_talk_addfriend).setView(view);
		alertDialog = builder.create();
		alertDialog.show();
	}
	
	public class BuddyTalkListFragment extends ListFragment {

		private CursorAdapter mAdapter = null;
		private List<Integer> arr_group = new ArrayList<Integer>();
		
		public final char HANGUL_BEGIN_UNICODE = 44032; // 가
		public final char HANGUL_END_UNICODE = 55203; // 힣
		public final char HANGUL_BASE_UNIT = 588;//각자음 마다 가지는 글자수
		public final char[] INITIAL_SOUND = { 'ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ',
	        'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ' };
		
		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			setHasOptionsMenu(true);
			
			searcdh_bar.setVisibility(View.VISIBLE);
			checkedPerson.clear();
			mAdapter = new BuddyTalkCursorAdapter(getActivity().getParent(), null, 0, checkedPerson, showcheckbox, arr_group);
//			setListAdapter(mAdapter);
			ListView listView = getListView();
			listView.setDivider(getResources().getDrawable(R.drawable.inbox_divider));
			listView.setDividerHeight(1);
			listView.setFastScrollEnabled(true);
			listView.setScrollingCacheEnabled(false);
			listView.setAdapter(mAdapter);
			queryHandler = new NotifyingAsyncQueryHandler(getActivity().getParent().getContentResolver(), onQueryReturn);
			queryHandler.startQuery(QUERY_BUDDY, null, BuddyTable.buildBuddyUnionUri(), null, 
					"(" + BuddyTable.KEY_BUDDY_CHOSUNG + " LIKE ?) OR (" + BuddyTable.KEY_BUDDY_DISPLAYNICK + " LIKE ?)", 
					new String[]{"%" + searchBuddy.getText().toString() + "%", "%" + searchBuddy.getText().toString() + "%"},
					null);
		}
		
		// 아이템 클릭 이벤트
		@Override
		public void onListItemClick(ListView l, View v, int position, long id) {
			super.onListItemClick(l, v, position, id);
			Cursor cursor = (Cursor) l.getItemAtPosition(position);
			int buddy_id = cursor.getInt(cursor.getColumnIndexOrThrow(BuddyTable._ID));
			long receiverMsb = cursor.getLong(cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_UUID_MSB));
			long receiverLsb = cursor.getLong(cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_UUID_LSB));
			String displayName  = cursor.getString(cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_DISPLAYNAME));
			int favorite = cursor.getInt(cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_FAVORITE));
			
			String selection = ContactTable.KEY_BUDDY_UUID_MSB + "=? AND " + ContactTable.KEY_BUDDY_UUID_LSB + "=?";
			String[] selectionArgs = {String.valueOf(receiverMsb), String.valueOf(receiverLsb)};
			Cursor cursor2 = getActivity().getContentResolver().query(ContactTable.CONTENT_URI, new String[] {ContactTable.KEY_CONTACT_PHONE_ID},
							selection, selectionArgs, null);
			// 연락처 소유 구분
			int raw_id = -1;
			try{
				while(cursor2.moveToNext()){
					raw_id = cursor2.getInt(cursor2.getColumnIndexOrThrow(ContactTable.KEY_CONTACT_PHONE_ID));
				}
			} finally{
				cursor2.close();
			}
			
			BuddyInfo buddyInfo = null;
			try {
				buddyInfo = BuddyInfo.parseFrom(cursor.getBlob(cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_INFO)));
			} catch (InvalidProtocolBufferMicroException e1) {
				e1.printStackTrace();
			} catch (IllegalArgumentException e1) {
				e1.printStackTrace();
			}
			goQuickAction(v, buddy_id, receiverMsb, receiverLsb, displayName, buddyInfo, raw_id, favorite, getActivity().getParent());
		}
		
		/**
		 * 현재 Buddy 변화 상태를 Observing 한다. 
		 */
		ContentObserver mBuddyObserver = new ContentObserver(new Handler()) {
			public void onChange(boolean selfChange) {
				queryHandler.startQuery(QUERY_BUDDY, null, BuddyTable.buildBuddyUnionUri(), null, 
						"(" + BuddyTable.KEY_BUDDY_CHOSUNG + " LIKE ?) OR (" + BuddyTable.KEY_BUDDY_DISPLAYNICK + " LIKE ?)", 
						new String[]{"%" + searchBuddy.getText().toString() + "%", "%" + searchBuddy.getText().toString() + "%"},
						null);
			};
		};
		
		@Override
		public void onResume() {
			super.onResume();
			searchBuddy.addTextChangedListener(watcher());
			getActivity().getParent().getContentResolver().registerContentObserver(BuddyTable.buildBuddyUnionUri(), true, mBuddyObserver);
			mBuddyObserver.onChange(true);
		}
		
		@Override
		public void onPause() {
			super.onPause();
			searchBuddy.removeTextChangedListener(watcher());
			getActivity().getParent().getContentResolver().unregisterContentObserver(mBuddyObserver);
			((InputMethodManager)getActivity().getParent().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(searchBuddy.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
		
		
		private void makeNameTag(Cursor data) {
			ArrayList<Character> char_group = new ArrayList<Character>();
			arr_group.clear();
			Cursor cursor = getActivity().getContentResolver().query(BuddyTable.CONTENT_URI, null, 
					"(" + BuddyTable.KEY_BUDDY_NEW_FRIEND + "=1 AND " + BuddyTable.KEY_BUDDY_STATUS_TYPE + "=1) AND ((" +
					BuddyTable.KEY_BUDDY_CHOSUNG + " LIKE ?) OR (" + BuddyTable.KEY_BUDDY_DISPLAYNICK + " LIKE ?))", 
					new String[]{"%" + searchBuddy.getText().toString() + "%", "%" + searchBuddy.getText().toString() + "%"}, null);
			data.moveToPosition(cursor.getCount()-1);
			cursor.close();
			while(data.moveToNext()){	// 0번째부터 다시 NameTag 생성
				 /** 초성을 판별하여 인덱스 생성*/
		        String a = data.getString(data.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_DISPLAYNICK));
		        if(a == null || "".equals(a)){
		        	a = " ";
		        }
		        char b = a.charAt(0);
		        char d;
		        if(b < HANGUL_BEGIN_UNICODE){
		        	d = b;
		        } else{
		        	d = INITIAL_SOUND[(b-HANGUL_BEGIN_UNICODE)/HANGUL_BASE_UNIT];
		        }
		        
		        if(!char_group.contains(d)) {
		        	char_group.add(d);
		        	if(!arr_group.contains(data.getPosition())) arr_group.add(data.getPosition());
		        }
			}
		}

		NotifyingAsyncQueryHandler.AsyncQueryListener onQueryReturn = new NotifyingAsyncQueryHandler.AsyncQueryListener() {
			@Override
			public void onQueryComplete(int token, Object cookie, Cursor cursor) {
				switch (token){
				case QUERY_BUDDY:
					getActivity().getParent().getParent().startManagingCursor(cursor);
					mAdapter.changeCursor(cursor);
					makeNameTag(cursor);
					Cursor cursor1 = getActivity().getContentResolver().query(BuddyTable.CONTENT_URI, BuddyTable.PROJECTION, 
							BuddyTable.KEY_BUDDY_NEW_FRIEND + "=1 AND " + BuddyTable.KEY_BUDDY_STATUS_TYPE + "=1", null, null);
					try{
						BuddyTabActivity.updateMnTalkBadge(cursor1.getCount());
					} finally {
						cursor1.close();
					}
					break;
				}
			}
			
			@Override
			public void onUpdateComplete(int token, Object cookie, int result) {
			}
			
			@Override
			public void onInsertComplete(int token, Object cookie, Uri uri) {
			}
			
			@Override
			public void onDeleteComplete(int token, Object cookie, int result) {
			}
		};
	}
	
	private void changeGroup() {
		BuddyTalkListFragment1 list = new BuddyTalkListFragment1();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.buddy_talk_list, list);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.commit();
    }
	
	private void changeShowAll(){
		BuddyTalkListFragment list = new BuddyTalkListFragment();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.buddy_talk_list, list);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.commit();
	}
	
	// Group MOde
	public class BuddyTalkListFragment1 extends ExpandableListFragment implements OnGroupClickListener, OnGroupCollapseListener,
																						OnGroupExpandListener, OnChildClickListener{
		private BaseExpandableListAdapter mAdapter;
		private ExpandableListView expandableListview;
		
		private List<GroupItem> group;
		private List<List<ChildrenItem>> child;
		
		private Handler mHandler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				default:
					break;
				}
			}
		};
		
		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			setHasOptionsMenu(true);
			
			searcdh_bar.setVisibility(View.GONE);
			mUiController = new BuddyTalkController(getActivity().getParent(), mHandler);
			
			initializeView();	// 뷰 정의
			initializeDataSet();
			
			mAdapter = new BuddyTalkExpandableListAdapter(getActivity().getParent(), R.layout.list_item_buddy_talk_group, R.layout.list_item_buddy_talk_child, showcheckbox, group, child, checkedPerson);
			
			ExpandableListView expandableListView = getExpandableListView();
			expandableListView.setDivider(getResources().getDrawable(R.drawable.inbox_divider));
			expandableListView.setChildDivider(getResources().getDrawable(R.drawable.inbox_divider));
			expandableListView.setDividerHeight(1);
			expandableListView.setFastScrollEnabled(true);
			expandableListView.setScrollingCacheEnabled(false);
			expandableListView.setAdapter(mAdapter);
//			setListAdapter(mAdapter);
			registerForContextMenu(getExpandableListView());
			queryHandler = new NotifyingAsyncQueryHandler(getActivity().getParent().getContentResolver(), onQueryReturn);
			queryHandler.startQuery(QUERY_BUDDY_GROUP, null, BuddyTable.CONTENT_URI, BuddyTable.PROJECTION, null, null, null);
		}
		
		/**
		 * 현재  BuddyGroup 변화 상태를 Observing 한다. 
		 */
		ContentObserver mBuddyGroupObserver = new ContentObserver(new Handler()) {
			public void onChange(boolean selfChange) {
				queryHandler.startQuery(QUERY_BUDDY_GROUP, null, BuddyTable.CONTENT_URI, BuddyTable.PROJECTION, null, null, null);
			};
		};
		
		@Override
	    public boolean onContextItemSelected(MenuItem item) {
	        ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();

	        String title = ((TextView) info.targetView).getText().toString();
	        
	        int type = ExpandableListView.getPackedPositionType(info.packedPosition);
	        if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
	            int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition); 
	            int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition); 
	            Toast.makeText(mContext, title + ": Child " + childPos + " clicked in group " + groupPos,
	                    Toast.LENGTH_SHORT).show();
	            return true;
	        } else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
	            int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition); 
	            Toast.makeText(mContext, title + ": Group " + groupPos + " clicked", Toast.LENGTH_SHORT).show();
	            return true;
	        }
	        return false;
	    }
		
		private void initializeDataSet() {
			checkedPerson = new ArrayList<BuddyUUIDItem>();
			group = new ArrayList<GroupItem>();
			child = new ArrayList<List<ChildrenItem>>();
		}

		private void initializeView() {
			expandableListview = getExpandableListView();
			
			expandableListview.setOnGroupClickListener(this);
			expandableListview.setOnGroupCollapseListener(this);
			expandableListview.setOnGroupExpandListener(this);
			expandableListview.setOnChildClickListener(this);

			expandableListview.setGroupIndicator(null);
			
			registerForContextMenu(expandableListview);
		}
		
		@Override
		public boolean onChildClick(ExpandableListView parent, View v,
				int groupPosition, int childPosition, long id) {
			int buddy_id = child.get(groupPosition).get(childPosition).id;
			long receiverMsb = child.get(groupPosition).get(childPosition).msb;
			long receiverLsb = child.get(groupPosition).get(childPosition).lsb;
			BuddyInfo buddyInfo = child.get(groupPosition).get(childPosition).buddyInfo;
			String displayName = child.get(groupPosition).get(childPosition).name;
			int favorite = child.get(groupPosition).get(childPosition).favorite;
			
			String selection = ContactTable.KEY_BUDDY_UUID_MSB + "=? AND " + ContactTable.KEY_BUDDY_UUID_LSB + "=?";
			String[] selectionArgs = {String.valueOf(receiverMsb), String.valueOf(receiverLsb)};
			Cursor cursor2 = mContext.getContentResolver().query(ContactTable.CONTENT_URI, new String[] {ContactTable.KEY_CONTACT_PHONE_ID},
							selection, selectionArgs, null);
			// 연락처 소유 구분
			int raw_id = -1;
			try{
				while(cursor2.moveToNext()){
					raw_id = cursor2.getInt(cursor2.getColumnIndexOrThrow(ContactTable.KEY_CONTACT_PHONE_ID));
				}
			} finally{
				cursor2.close();
			}
			goQuickAction(v, buddy_id, receiverMsb, receiverLsb, displayName, buddyInfo, raw_id, favorite, getActivity().getParent());
			
			return true;
		}

		@Override
		public void onGroupExpand(int groupPosition) {
			
		}

		@Override
		public void onGroupCollapse(int groupPosition) {
			
		}

		@Override
		public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
			return false;
		}
		
		@Override
		public void onResume() {
			super.onResume();
			getActivity().getParent().getContentResolver().registerContentObserver(BuddyTable.CONTENT_URI, true, mBuddyGroupObserver);
			initGroupView();
		}
		
		@Override
		public void onPause() {
			super.onPause();
			getActivity().getParent().getContentResolver().unregisterContentObserver(mBuddyGroupObserver);
		}
		
		private void initGroupView() {		
//			checkedPerson.clear();
			group.clear();
			child.clear();
			
			BuddyTalkExpandableListAdapter.createDataSet(getActivity().getParent(), group, child);
			mAdapter.notifyDataSetChanged();
			
			expandList();
		}

		private void expandList() {
			for (int i=0; i<group.size(); i++) {
				if(group.get(i).fold == 0) expandableListview.expandGroup(i);
			}
		}
		
		NotifyingAsyncQueryHandler.AsyncQueryListener onQueryReturn = new NotifyingAsyncQueryHandler.AsyncQueryListener(){

			@Override
			public void onQueryComplete(int token, Object cookie, Cursor cursor) {
				switch (token){
				case QUERY_BUDDY_GROUP:
					getActivity().getParent().startManagingCursor(cursor);
					initGroupView();
					break;
				}
			}

			@Override
			public void onInsertComplete(int token, Object cookie, Uri uri) {
			}

			@Override
			public void onUpdateComplete(int token, Object cookie, int result) {
			}

			@Override
			public void onDeleteComplete(int token, Object cookie, int result) {
			}
		};
	}
	
	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.btn_groupChat){
			if(checkedPerson.size() >= 2){
				List<UserBasicInfo> list = new ArrayList<UserBasicInfo>();
				for(BuddyUUIDItem item : checkedPerson){
					list.add(new UserBasicInfo().setUserUuid(new GpbSupport().makeUuidMsg(item.msb, item.lsb))
							.setDisplayName(item.name));
				}
				mInboxController.startGroupChat(list);
			} else {
				Toast.makeText(mContext, "Select more than 2 persons", Toast.LENGTH_SHORT).show();
			}
		} else if(v.getId() == R.id.btn_groupMessage){
			if(checkedPerson.size() >= 2){
				List<UserBasicInfo> list = new ArrayList<UserBasicInfo>();
				for(BuddyUUIDItem item : checkedPerson){
					list.add(new UserBasicInfo().setUserUuid(new GpbSupport().makeUuidMsg(item.msb, item.lsb))
							.setDisplayName(item.name));
				}
				mInboxController.startBroadcastChat(list);
			} else {
				Toast.makeText(mContext, "Select more than 2 persons", Toast.LENGTH_SHORT).show();
			}
		} else if(v.getId() == R.id.btn_cancel){
			showcheckbox = false;
			layout.setVisibility(View.GONE);
			if(mode == SHOW_GROUP) changeGroup();
			else changeShowAll();
		} 
	}
	
	private static void goQuickAction(View v, int buddy_id, long receiverMsb, long receiverLsb, String displayName, BuddyInfo buddyInfo, int raw_id, int favorite, Activity activity) {
		try {
			// 액션 바를 띄워준다.
			QuickAction quickAction = new QuickAction(v.findViewById(R.id.buddy_child_profile));
			quickAction.addActionItem(new BuddyActionItem(activity, ItemType.ONE_TO_ONE, buddy_id, receiverMsb, receiverLsb, buddyInfo, displayName, raw_id, favorite, quickAction));
			if(raw_id != -1){
				quickAction.addActionItem(new BuddyActionItem(activity, ItemType.SEND_MESSAGE, buddy_id, receiverMsb, receiverLsb, buddyInfo, displayName, raw_id, favorite, quickAction));
				quickAction.addActionItem(new BuddyActionItem(activity, ItemType.CALL, buddy_id, receiverMsb, receiverLsb, buddyInfo, displayName, raw_id, favorite, quickAction));
			}
			quickAction.addActionItem(new BuddyActionItem(activity, ItemType.PROFILEVIEW, buddy_id, receiverMsb, receiverLsb, buddyInfo, displayName, raw_id, favorite, quickAction));
			quickAction.addActionItem(new BuddyActionItem(activity, ItemType.FAVORITE, buddy_id, receiverMsb, receiverLsb, buddyInfo, displayName, raw_id, favorite, quickAction));
//			quickAction.addActionItem(new BuddyActionItem(mContext, ItemType.INVITE, buddy_id, receiverMsb, receiverLsb, buddyInfo, displayName, raw_id, favorite, quickAction));
			quickAction.setAnimStyle(QuickAction.ANIM_AUTO);
			quickAction.setMode(QuickAction.MODE_DIALOG);
			quickAction.show();
		} catch (IllegalArgumentException e) {
			MTalkLogWriter.e(e);
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
	}
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if(showcheckbox == true && keyCode == KeyEvent.KEYCODE_BACK){
			showcheckbox = false;
			layout.setVisibility(View.GONE);
			if(mode == SHOW_GROUP) changeGroup();
			else changeShowAll();
			
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		ContentValues cv = new ContentValues();
		cv.put(BuddyTable.KEY_BUDDY_NEW_FRIEND, 0);
		String where = BuddyTable.KEY_BUDDY_NEW_FRIEND + "=1";
		mContext.getContentResolver().update(BuddyTable.CONTENT_URI, cv, where, null);
	}
}
